package com.qing.microservices.shirostudy.common.matcher;

import cn.hutool.crypto.digest.SM3;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.util.ByteSource;

import java.nio.charset.StandardCharsets;

/**
 * @author guoqf
 */
@Slf4j
public class Sm3SimpleCredentialsMatcher extends SimpleCredentialsMatcher {

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        Object tokenHashedCredentials = hashProvidedCredentials(token, info);
        Object accountCredentials = getCredentials(info);
        return equals(tokenHashedCredentials, accountCredentials);
    }


    private Object hashProvidedCredentials(AuthenticationToken token, AuthenticationInfo info) {
        ByteSource salt = ((SimpleAuthenticationInfo) info).getCredentialsSalt();
        char[] password = ((UsernamePasswordToken) token).getPassword();
        String pwd = String.valueOf(password);
        SM3 digest;
        if (salt != null) {
            byte[] bytes = salt.getBytes();
            log.info("用户[{}]的加密盐[{}]", info.getPrincipals(), new String(bytes, StandardCharsets.UTF_8));
            digest = new SM3(bytes);
        } else {
            digest = new SM3();
        }
        return digest.digestHex(pwd);
    }
}
